<template>
  <div class="awsCenter">
    <div style="width: 100%; height: 560px; display: flex; flex-direction: column; align-items: center;">
      <!-- 按钮栏 -->
      <div class="awsCenter" style="width: 100%; height: 40px;">
        <el-select clearable v-model="type" placeholder="纹样类型" style="width: 150px">
          <el-option v-for="item in typeList" :key="item" :label="item" :value="item" />
        </el-select>
        <el-input clearable v-model="region" placeholder="地域分布" style="width: 150px; margin-left: 10px" />
        <el-select clearable v-model="difficultyLevel" placeholder="工艺难度" style="width: 120px; margin-left: 10px">
          <el-option v-for="item in difficultyLevelList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select clearable v-model="status" placeholder="状态" style="width: 120px; margin-left: 10px">
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>

        <el-button @click="fetchPatternList(true)" style="width: 80px; margin-left: 10px" type="primary" plain>查询</el-button>
        <el-button style="width: 80px; margin-left: auto" type="primary" @click="openDialog('新增纹样')">新增</el-button>
        <el-button @click="delAll">批量删除</el-button>
      </div>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        stripe
        style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange"
        :row-style="{ height: '40px' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="纹样名称" width="150" />
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="region" label="地域" width="120" />
        <el-table-column prop="difficultyLevel" label="难度" width="100" />
        <el-table-column label="文化寓意" width="180">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="300">
              <template #default>
                <div>文化寓意: {{ scope.row.culturalMeaning }}</div>
                <div v-if="scope.row.historicalBackground">历史背景: {{ scope.row.historicalBackground }}</div>
              </template>
              <template #reference>
                <el-tag size="default" >{{ scope.row.culturalMeaning?.substring(0, 20) }}</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="纹样" width="120">
          <template #default="{ row }">
            <el-image style="width: 35px" :src="row.templateFilePath"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="patternRole" label="构图角色" width="100" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button type="primary" plain :icon="Edit" circle @click="openDialog('编辑纹样', row)" />
            <el-button type="danger" plain :icon="Delete" circle @click="handleDelete(row)" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="demo-pagination-block" style="margin-top: 20px">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="7"
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="showDialog"
        width="900px"
        align-center
        :close-on-click-modal="false"
        @close="resetForm"
        :destroy-on-close="true"
      >
        <el-form
          :model="form"
          label-position="top"
          label-width="100px"
          style="height: 540px; overflow: auto;"
        >
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="base">
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="纹样名称" prop="name">
                    <el-input v-model="form.name" placeholder="如：蟒龙纹" />
                  </el-form-item>

                  <el-form-item label="纹样类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择" style="width: 100%">
                      <el-option v-for="item in typeList" :key="item" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="地域分布" prop="region">
                    <el-input v-model="form.region" placeholder="如：广西靖西" />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="难度等级" prop="difficultyLevel">
                    <el-select v-model="form.difficultyLevel" placeholder="请选择" style="width: 100%">
                      <el-option v-for="item in difficultyLevelList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="构图角色" prop="patternRole">
                    <el-select v-model="form.patternRole" placeholder="请选择" style="width: 100%">
                      <el-option v-for="item in patternRoleList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
                      <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <!-- 纹样图片上传（居中，占满一行） -->
                <el-col :span="24">
                  <el-form-item label="纹样图片">
                    <div class="upload-container">
                      <el-upload
                        :action="UploadUrl()"
                        class="avatar-uploader"
                        :show-file-list="false"
                        @change="onFileChange"
                        :before-upload="beforeUpload"
                        :http-request="customUpload"
                      >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                      </el-upload>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <el-tab-pane label="文化与工艺" name="culture">
              <el-form-item label="文化寓意" prop="culturalMeaning">
                <el-input
                  v-model="form.culturalMeaning"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入文化寓意"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="历史背景" prop="historicalBackground">
                <el-input
                  v-model="form.historicalBackground"
                  type="textarea"
                  :rows="3"
                  placeholder="可选：典故、起源等"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="工艺流程" prop="craftProcess">
                <el-input
                  v-model="form.craftProcess"
                  type="textarea"
                  :rows="3"
                  placeholder="可选：传统制作步骤"
                  style="width: 100%"
                />
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form>

        <template #footer>
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  getPatternList,
  delPattern,
  savePattern,
  getPatternById,
  updatePattern
} from '@/api/patternLibrary.js'
import { onMounted, ref } from 'vue'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// ✅ 引入你自己的 upload 工具函数（请确保路径正确）
import { upload } from '@/api/upload.js'

// 分页
const currentPage = ref(1)
const total = ref(0)
const tableData = ref([])

// 筛选条件
const type = ref('')
const region = ref('')
const difficultyLevel = ref('')
const status = ref('')

// 下拉选项
const typeList = ref(['几何纹', '动物纹', '植物纹', '文字纹', '人物纹', '抽象纹'])

const difficultyLevelList = [
  { value: '初级', label: '初级' },
  { value: '中级', label: '中级' },
  { value: '高级', label: '高级' }
]

const statusList = [
  { value: '正常', label: '正常' },
  { value: '下架', label: '下架' },
  { value: '待更新', label: '待更新' }
]

const patternRoleList = [
  { value: '主纹', label: '主纹' },
  { value: '辅纹', label: '辅纹' },
  { value: '边饰', label: '边饰' }
]

// 表单
const showDialog = ref(false)
const dialogTitle = ref('')
const activeTab = ref('base')
const form = ref({
  id: null,
  name: '',
  type: '',
  region: '',
  difficultyLevel: '',
  culturalMeaning: '',
  historicalBackground: '',
  craftProcess: '',
  templateFilePath: '', // 存储图片 URL
  status: '正常',
  patternRole: ''
})

const selectedRows = ref([])

// 初始化
onMounted(() => {
  fetchPatternList(false)
})

// 获取列表
const fetchPatternList = async (showMsg = false) => {
  const res = await getPatternList({
    current: currentPage.value,
    pageSize: 7,
    type: type.value,
    region: region.value,
    difficultyLevel: difficultyLevel.value,
    status: status.value
  })
  console.log({
    current: currentPage.value,
    pageSize: 7,
    type: type.value,
    region: region.value,
    difficultyLevel: difficultyLevel.value,
    status: status.value
  })
  if (res.code === 200) {
    tableData.value = res.data.data
    total.value = res.data.total
    if (showMsg) ElMessage.success('查询成功')
  }
}

// 分页切换
const handleCurrentChange = (page: number) => {
  currentPage.value = page

  fetchPatternList()
}

// 选择行
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 批量删除
const delAll = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择数据')
    return
  }
  ElMessageBox.confirm('确定删除选中的纹样？', '批量删除', {
    type: 'warning'
  }).then(async () => {
    const ids = selectedRows.value.map(r => r.id)
    const res = await delPattern(ids)
    if (res.code === 200) {
      ElMessage.success(res.message)
      await fetchPatternList()
    }else{
      ElMessage.warning(res.message)
    }
  })
}

// 单删
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除纹样【${row.name}】？`, '删除确认', {
    type: 'warning'
  }).then(async () => {
    const res = await delPattern([row.id])
    if (res.code === 200) {
      ElMessage.success(res.message)
      await fetchPatternList()
    }else{
      ElMessage.warning(res.message)
    }
  })
}

// 打开弹窗
const openDialog = async (title: string, row = null) => {
  dialogTitle.value = title
  showDialog.value = true
  activeTab.value = 'base'

  if (row) {
    const res = await getPatternById(row.id)
    if (res.code === 200) {
      Object.assign(form.value, res.data)
      imageUrl.value=form.value.templateFilePath
    }

  } else {
    resetForm()
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    name: '',
    type: '',
    region: '',
    difficultyLevel: '',
    culturalMeaning: '',
    historicalBackground: '',
    craftProcess: '',
    templateFilePath: '',
    status: '正常',
    patternRole: ''
  }
  imageUrl.value=''
}

// 提交表单
const submitForm = async () => {
  const { name, type, culturalMeaning, templateFilePath } = form.value
  if (!name || !type || !culturalMeaning) {
    ElMessage.warning('请填写必填项')
    return
  }
  if (!templateFilePath) {
    ElMessage.warning('请上传纹样图片')
    return
  }

  let res
  if (form.value.id) {
    res = await updatePattern(form.value)
  } else {
    res = await savePattern(form.value)
  }

  if (res.code === 200) {
    ElMessage.success(res.message)
    await fetchPatternList()
    showDialog.value = false
  } else {
    ElMessage.error(res.errMsg || '操作失败')
  }
}

// ✅ 上传前校验：仅允许 .png，≤2MB
const beforeUpload = (file: File) => {
  const isValidType = file.type === 'image/png' || file.name.toLowerCase().endsWith('.png')
  if (!isValidType) {
    ElMessage.error('仅支持 PNG 格式图片！')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const UploadUrl = () => {
  // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，
  // 所以这里将action设置为一个返回为空的方法就行，避免抛错
  return ""
}
const imageUrl = ref('')

const onFileChange=(async (file)=>{
  //console.log(file)
  imageUrl.value = URL.createObjectURL(file.raw!)
  const res=await upload(file.raw)
  //console.log(res)
  if (res.code===200){
    form.value.templateFilePath=res.message
  }
})


const customUpload = async (options: any) => {

}

// 状态标签颜色
const getStatusType = (status: string) => {
  if (status === '正常') return 'success'
  if (status === '下架') return 'danger'
  return 'warning'
}
</script>

<style scoped>
.awsCenter {
  display: flex;
  align-items: center;
}

/* 上传区域容器：居中、限制最大宽度 */
.upload-container {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

/* 上传组件样式 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}
.avatar {
  width: 160px;
  height: 160px;
  display: block;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}
</style>
